package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private final StringRedisTemplate stringRedisTemplate;

    private final IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        UserDTO user = UserHolder.getUser();
        if (isFollow) {
            Follow follow = new Follow();
            follow.setUserId(user.getId());
            follow.setFollowUserId(followUserId);
            boolean success = save(follow);
            if (success) {
                // 将被关注的用户加入到当前用户的关注列表中
                stringRedisTemplate.opsForSet().add("follows:" + user.getId(), followUserId.toString());
            }
        }
        else {
            boolean success = removeById(followUserId);
            if (success) {
                stringRedisTemplate.opsForSet().remove("follows:" + user.getId(), followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        UserDTO user = UserHolder.getUser();
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        queryWrapper.eq("follow_user_id", followUserId);
        boolean exists = count(queryWrapper) > 0;
        return Result.ok(exists);
    }

    @Override
    public Result followCommons(Long id) {
        UserDTO user = UserHolder.getUser();
        String key1 = "follows:" + user.getId();
        String key2 = "follows:" + id;
        // 利用redis set集合交运算得到共同关注列表
        Set<String> common = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (common == null || common.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> idList = common.stream().map(Long::parseLong).collect(Collectors.toList());
        List<UserDTO> collect = userService.listByIds(idList)
                .stream()
                .map(user1 -> BeanUtil.copyProperties(user1, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(collect);
    }
}
